package com.rabincorp.euro2012.support;

import javax.persistence.EntityManager;

import com.rabincorp.euro2012.entity.Admin;
import com.rabincorp.euro2012.entity.User;

public class UserSession {

	public enum Type {
		User, Admin;
	}

	private Long id;
	private Type type;

	private EntityManager em;

	public UserSession(Long id, Type type, EntityManager em) {
		super();
		this.id = id;
		this.type = type;
		this.em = em;
	}

	public boolean isValid() {
		return id != null && id > 0;
	}

	public Type getType() {
		return type;
	}

	public void ensureLoginAsUser() {
		if (Type.User != type) {
			throw new ServiceException("must login as user");
		}
	}

	public void ensureLoginAsAdmin() {
		if (Type.Admin != type) {
			throw new ServiceException("must login as admin");
		}
	}

	public User asUser() {
		ensureLoginAsUser();

		return em.find(User.class, id);
	}

	public Admin asAdmin() {
		ensureLoginAsAdmin();
		return em.find(Admin.class, id);
	}
}
